#pragma once
#include <iostream>
#include <vector>
#include <queue>
#include <memory>
#include <pthread.h>

#include "log.hpp" // 引⼊⾃⼰的⽇志
#include "thread.hpp" // 引⼊⾃⼰的线程
#include "lock.hpp" // 引⼊⾃⼰的锁
#include "cond.hpp" // 引⼊⾃⼰的条件变量

namespace ThreadPoolModule
{

    using namespace ThreadModule;
    using namespace CondMoudle;
    using namespace MutexModule;
    using namespace LogModule;

    const static int gdefaultthreadnum = 10;

    template<class T>
    class ThreadPool
    {
    private:
        void WakeUpAllThread()
        {
            LockGuard lockguard(_mutex);
            if (_sleepernum)
                _cond.Broadcast();
            LOG(LogLevel::INFO) << "唤醒所有的休眠线程";
        }
        void WakeUpOne()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << "唤醒一个休眠线程";
        }
        ThreadPool(int num = gnum) : _num(num), _isrunning(false), _sleepernum(0)
        {   
            for(int i = 0; i < num; i++)
            {
                _threads.emplace_back(
                    [this]()
                    {
                        HandleTask();
                    }
                );
            }
        }

        void Start()
        {
            if(_isrunning)
                return;

            _isrunning = true;
            for(auto& thread : threads)
            {
                thread.Start();
                 LOG(LogLevel::INFO) << "start new thread success: " << thread.Name();
            }
        }
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;
    public:
        static ThreadPool<T> *GetInstance()
        {
            if(inc == nullptr)
            {
                LockGuard lockguard(_lock);

                LOG(LogLevel::DEBUG) << "获取首次单例";
                if(inc == nullptr)
                {
                    LOG(LogLevel::DEBUG) << "首次使用单例，创建...";
                    inc = new ThreadPool<T>();
                    inc -> Start();
                }
            }
        }
        void HandleTask()
        {
            char name[128];
            pthread_setname_np(pthread_self(), name, sizeof(name));

            while(true)
            {
                T t;
                {
                    LockGuard lockguard(_mutex);
                    //1.    a.队列为空   b.线程也没有退出
                    while(_taskq.empty() && _isrunning)
                    {
                        _sleepernum++; // 记录等待的线程数
                        _cond.Wait(_mutex.GetMutex()); // 释放锁并等待
                        _sleepernum--; // 被唤醒后减少等待计数                    }
                    }

                    //2.内部线程被唤醒
                    if(!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::DEBUG) << "线程安全退出，线程池退出&&任务队列为空";
                        break;
                    }

                    //一定有任务
                    t = _taskq.front();
                    _taskq.pop();
                }
                t();
            }
        }

        // void InitThreadPool()
        // {}
        void Stop()
        {
            if (!_isrunning)
                return;
            _isrunning = false;

            // 唤醒所有的线层
            WakeUpAllThread();
        }
        void Join()
        {
            for(auto& thread : _threads)
            {
                thread.Join();
            }
        }
        bool Enqueue(const T &t)
        {
            if(_isrunning)
            {
                LockGuard lockguard(_mutex);
                _taskq.push(in);
                if(_threads.size() == _sleepernum)
                {
                    WakeUpOne();
                }
                return true;
            }
            retrun false;
        }
        ~ThreadPool()
        {}

    private:
        std::vector<Thread> _threads;
        int _num; // 线程池中，线程的个数
        std::queue<T> _taskq;
        cond _cond;
        Mutex _mutex;

        bool _isrunning;
        int _sleepernum;

        // bug??
        static ThreadPool<T> *inc; // 单例指针
        static Mutex _lock;
    };

}